package com.itstudio.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itstudio.portal.entity.AuthInfo;
import com.itstudio.portal.entity.RestResponse;
import com.itstudio.portal.entity.User;
import com.itstudio.portal.entity.dto.AuthInfoDto;
import com.itstudio.portal.entity.dto.AuthQueryDto;
import com.itstudio.portal.entity.dto.CorporateMaintenanceDto;
import com.itstudio.portal.entity.vo.AuthInfoVo;
import com.itstudio.portal.entity.vo.CorporateMaintenanceVo;
import com.itstudio.portal.enums.HttpCodeEnum;
import com.itstudio.portal.mapper.AuthInfoMapper;
import com.itstudio.portal.mapper.UserMapper;
import com.itstudio.portal.service.AuthInfoService;
import com.itstudio.portal.utils.BeanCopyUtil;
import com.itstudio.portal.utils.IndustryUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Description:
 * @Author: zhaopengbo
 * @Date: 2024/11/12
 */
@Slf4j
@Service("authInfoService")
public class AuthInfoServiceImpl extends ServiceImpl<AuthInfoMapper, AuthInfo> implements AuthInfoService {
    @Autowired
    AuthInfoMapper authInfoMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    IndustryUtil industryUtil;

    @Override
    @Transactional
    public RestResponse<Map<String,Long>> submitAuthInfo(AuthInfoDto authInfoDto) {
        LambdaQueryWrapper<AuthInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AuthInfo::getUserId, authInfoDto.getUserId());
        Long count = authInfoMapper.selectCount(queryWrapper);
        if (count > 0) {
            return RestResponse.failure(HttpCodeEnum.AUTH_INFO_IS_EXIST);
        }

        if (!StringUtils.hasText(authInfoDto.getBusinessLicense())) {
            return RestResponse.failure(HttpCodeEnum.BUSINESS_LICENSE_NOT_NULL);
        }
        if (!StringUtils.hasText(authInfoDto.getBusinessAddress())) {
            return RestResponse.failure(HttpCodeEnum.BUSINESS_ADDRESS_NOT_NULL);
        }
        if (!StringUtils.hasText(authInfoDto.getMainDescription())){
            return RestResponse.failure(HttpCodeEnum.MAIN_DESCRIPTION_NOT_NULL);
        }
//        if (authInfoDto.getBusinessPeriodStart() == null || ((authInfoDto.getBusinessPeriodEnd() == null && !authInfoDto.getBusinessPeriodLong().equals(1)))) {
//            return RestResponse.failure(HttpCodeEnum.BUSINESS_PERIOD_START_NOT_NULL);
//        }


        if (!StringUtils.hasText(authInfoDto.getIndustry())) {
            return RestResponse.failure(HttpCodeEnum.INDUSTRY_NOT_NULL);
        }

        AuthInfo authInfo = BeanCopyUtil.classVo(authInfoDto, AuthInfo.class);
        User user = BeanCopyUtil.classVo(authInfoDto, User.class);
        user.setId(authInfo.getUserId());
        user.setType("1");
        int userResult = userMapper.updateById(user);
        if (userResult == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RestResponse.failure(HttpCodeEnum.UNKNOWN_ERROR);
        }
        int authResult = authInfoMapper.insert(authInfo);
        if (authResult == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RestResponse.failure(HttpCodeEnum.UNKNOWN_ERROR);
        }
        /*
        UserRole userRole = new UserRole();
        userRole.setUserId(authInfo.getUserId());
        userRole.setRoleId(authInfo.getRoleId());
        userRoleMapper.deleteById(authInfo.getUserId());
        int result = userRoleMapper.insert(userRole);
        if (result == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RestResponse.failure(HttpCodeEnum.UNKNOWN_ERROR);
        }
         */
        Map<String,Long> idMap = new HashMap<>();
        idMap.put("id",authInfo.getId());
        return RestResponse.success(idMap);
    }

    @Override
    @Transactional
    public RestResponse updateAuthInfo(AuthInfoDto authInfoDto) {
        LambdaQueryWrapper<AuthInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AuthInfo::getUserId, authInfoDto.getUserId());
        queryWrapper.eq(AuthInfo::getId,authInfoDto.getId());
        Long count = authInfoMapper.selectCount(queryWrapper);
        if (count == 0) {
            return RestResponse.failure(HttpCodeEnum.NO_FIND_INFO);
        }
        AuthInfo authInfo = BeanCopyUtil.classVo(authInfoDto, AuthInfo.class);
        User user = BeanCopyUtil.classVo(authInfoDto, User.class);
        user.setId(authInfo.getUserId());
        user.setType("1");
        userMapper.updateById(user);

        authInfo.setStatus(0);
        int result = authInfoMapper.updateById(authInfo);
        if (result == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RestResponse.failure(HttpCodeEnum.UNKNOWN_ERROR);
        }

        return RestResponse.success();
    }

    @Override
    public RestResponse updateMaintenance(CorporateMaintenanceDto maintenanceDto) {
        LambdaQueryWrapper<AuthInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AuthInfo::getId, maintenanceDto.getId());
        AuthInfo authInfo = BeanCopyUtil.classVo(maintenanceDto, AuthInfo.class);
        int result = authInfoMapper.updateById(authInfo);
        if (result == 0) {
            return RestResponse.failure(HttpCodeEnum.UNKNOWN_ERROR);
        }
        return RestResponse.success();
    }

    @Override
    public RestResponse<CorporateMaintenanceVo> getMaintenance(Long userId){
        LambdaQueryWrapper<AuthInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AuthInfo::getUserId, userId);
        AuthInfo authInfo = authInfoMapper.selectOne(queryWrapper);
        if (authInfo == null) {
            return RestResponse.failure(HttpCodeEnum.AUTH_INFO_NOT_EXIST);
        }
        CorporateMaintenanceVo corporateMaintenanceVo = BeanCopyUtil.classVo(authInfo, CorporateMaintenanceVo.class);
        return RestResponse.success(corporateMaintenanceVo);
    }

    @Override
    public RestResponse selectAuthInfo(Long userId, Long id) {
        LambdaQueryWrapper<AuthInfo> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(AuthInfo::getUserId, userId);
        queryWrapper.eq(id != null, AuthInfo::getId, id);

        if (!authInfoMapper.exists(queryWrapper)) {
            return RestResponse.failure(HttpCodeEnum.AUTH_INFO_NOT_EXIST);
        }

        AuthInfoVo authInfoVo = authInfoMapper.selectAuthInfoWithUserWithRole(userId, id);
        if (authInfoVo == null) {
            return RestResponse.failure(HttpCodeEnum.RESULT_IS_NULL);
        }
//        Map<String, Map<String, String>> industryMap = industryUtil.parseIndustry(authInfoVo.getIndustry());
//        authInfoVo.setIndustryIds(industryMap);
//        if(Objects.equals(authInfoVo.getStatus(), Integer.valueOf(Const.STATUS_ZERO))){
//            return RestResponse.failure(HttpCodeEnum.AUTH_INFO_NOT_PASS);
//        }
        return RestResponse.success(authInfoVo);
    }

    @Override
    public RestResponse selectAllAuthInfo(AuthQueryDto authQueryDto) {

        List<AuthInfoVo> authInfoVoList = authInfoMapper.selectAuthInfoByCondition(authQueryDto);
//        List<AuthInfo> authInfos = authInfoMapper.selectList(null);
        return RestResponse.success(authInfoVoList);
    }
    @Transactional
    @Override
    public RestResponse deleteAuthInfo(long id) {
        LambdaQueryWrapper<AuthInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AuthInfo::getId, id);
        AuthInfo authInfo = authInfoMapper.selectOne(queryWrapper);

        if (authInfo == null) {
            return RestResponse.failure(HttpCodeEnum.ID_NOT_EXIST);
        }
        User user = new User();
        user.setId(id);
        user.setType("0");
        userMapper.updateById(user);
        int result = authInfoMapper.deleteById(id);
        if (result == 0) {
            log.error("deleteAuthInfo failed");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RestResponse.failure(HttpCodeEnum.UNKNOWN_ERROR);
        }
        /*
        int userRoleResult = userRoleMapper.deleteById(authInfo.getUserId());
        if (userRoleResult == 0) {
            log.error("deleteAuthInfo failed");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RestResponse.failure(HttpCodeEnum.UNKNOWN_ERROR);
        }

         */
        return RestResponse.success();
    }

}
